<template>
  <div class="text-align">
    <div class="card">
      <div class="card-header">
        <img class="logo-img" src="/logo_02.png" alt="logo" />
        文本对齐
      </div>

      <div class="lang-grid">
        <div class="select-area">
          <div class="select-title">
            <i class="fas fa-globe-asia"></i>
            <span>源语言</span>
          </div>
          <el-select v-model="sourceLang" placeholder="请选择源语言" class="full-width">
            <el-option label="中文" value="zh" />
            <el-option label="越南语" value="vi" />
            <el-option label="泰语" value="th" />
            <el-option label="印尼语" value="ms" />
            <el-option label="马来语" value="id" />
            <el-option label="塔加洛语" value="tl" />
            <el-option label="老挝语" value="lo" />
            <el-option label="僧伽罗语" value="si" />
            <el-option label="缅甸语" value="my" />
          </el-select>
        </div>

        <div class="select-area">
          <div class="select-title">
            <i class="fas fa-flag"></i>
            <span>目标语言</span>
          </div>
          <el-select v-model="targetLang" placeholder="请选择目标语言" class="full-width">
            <el-option label="中文" value="zh" />
            <el-option label="越南语" value="vi" />
            <el-option label="泰语" value="th" />
            <el-option label="印尼语" value="ms" />
            <el-option label="马来语" value="id" />
            <el-option label="塔加洛语" value="tl" />
            <el-option label="老挝语" value="lo" />
            <el-option label="僧伽罗语" value="si" />
            <el-option label="缅甸语" value="my" />
          </el-select>
        </div>
      </div>

      <div class="upload-grid">
        <div class="upload-section upload-area">
          <div class="upload-title">
            <i class="fas fa-file-upload"></i>
            <span>源文件</span>
          </div>
          <el-upload
            action="#"
            :file-list="displayFileList1"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange1"
            accept=".txt"
          >
            <el-button type="primary" :loading="loading">选择源文件</el-button>
          </el-upload>
          <span v-if="sourceFileName" class="file-name">{{ sourceFileName }}</span>
        </div>

        <div class="upload-section upload-area">
          <div class="upload-title">
            <i class="fas fa-file-import"></i>
            <span>目标文件</span>
          </div>
          <el-upload
            action="#"
            :file-list="displayFileList2"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange2"
            accept=".txt"
          >
            <el-button type="success" :loading="loading">选择目标文件</el-button>
          </el-upload>
          <span v-if="targetFileName" class="file-name">{{ targetFileName }}</span>
        </div>
      </div>

      <div class="btn-group">
        <el-button 
          class="btn-primary"
          @click="submitAlign" 
          :loading="loading" 
          type="primary"
          :disabled="!selectedFile1 || !selectedFile2"
        >
          开始对齐
        </el-button>
      </div>

      <div v-if="loading" class="loading-indicator">
        <el-icon><Loading /></el-icon>
        正在对齐，请稍候...
      </div>

      <el-alert 
        v-if="errorMessage" 
        :title="errorMessage" 
        type="error" 
        class="mt-15"
        show-icon 
        closable
        @close="errorMessage = ''"
      />
    </div>

    <div v-if="result" class="card">
      <div class="card-header small">对齐结果</div>
      <div class="result-section result-box">
        <div class="result-toolbar">
          <div />
          <div class="right-tools">
            <el-button size="small" text @click="downloadResult">导出文件</el-button>
          </div>
        </div>
        <div class="result-meta">
          <el-alert :title="result.message" type="success" show-icon />
          <p class="result-summary">
            对齐 {{ result.aligned_count }} / {{ resultLang1Name }} {{ result.total1 }} 行，{{ resultLang2Name }} {{ result.total2 }} 行
          </p>
        </div>
        <el-collapse>
          <el-collapse-item title="对齐结果预览（最多显示 50 条）">
            <el-table :data="alignedPairs" border style="width: 100%">
              <el-table-column :label="resultLang1Name" width="360">
                <template #default="scope">
                  {{ scope.row.text1 }}
                </template>
              </el-table-column>
              <el-table-column :label="resultLang2Name" width="360">
                <template #default="scope">
                  {{ scope.row.text2 }}
                </template>
              </el-table-column>
              <el-table-column prop="similarity" label="相似度" width="120">
                <template #default="scope">
                  {{ (scope.row.similarity * 100).toFixed(1) }}%
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
  <div class="back-btn">
    <back-button></back-button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'
import { Loading } from '@element-plus/icons-vue'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

// 仅用于显示文件名（给 el-upload 的 file-list）
const displayFileList1 = ref([])
const displayFileList2 = ref([])
const alignedPairs = ref([])  // 存储对齐结果
// 原始的选择上传的 File 对象
const selectedFile1 = ref(null)
const selectedFile2 = ref(null)
const loading = ref(false)
const result = ref(null)
const errorMessage = ref('')
const sourceFileName = ref('')
const targetFileName = ref('')
const sourceLang = ref('zh')
const targetLang = ref('vi')

// 语言映射
const languageNames = {
  'zh': '中文',
  'vi': '越南语',
  'th': '泰语',
  'ms': '马来语',
  'id': '印尼语',
  'tl': '塔加洛语',
  'km': '高棉语',
  'lo': '老挝语',
  'my': '缅甸语',
  'si': '僧伽罗语'
}

// 计算属性：动态语言标签
const resultLang1Name = computed(() => result.value ? languageNames[result.value.lang1] || result.value.lang1 : '')
const resultLang2Name = computed(() => result.value ? languageNames[result.value.lang2] || result.value.lang2 : '')

const handleChange1 = (file) => {
  if (file && file.raw) {
    // file.raw：原始的 File 对象，包含实际的文件数据
    selectedFile1.value = file.raw;
    sourceFileName.value = file.name;
    // displayFileList1：传递给 el-upload 组件的文件列表，用于界面展示
    displayFileList1.value = [{ name: file.name, url: '' }];
    errorMessage.value = ''; // 清除错误信息
  } else {
    selectedFile1.value = null;
    sourceFileName.value = '';
    displayFileList1.value = [];
  }
}

const handleChange2 = (file) => {
  if (file && file.raw) {
    selectedFile2.value = file.raw;
    targetFileName.value = file.name;
    displayFileList2.value = [{ name: file.name, url: '' }];
    errorMessage.value = ''; // 清除错误信息
  } else {
    selectedFile2.value = null;
    targetFileName.value = '';
    displayFileList2.value = [];
  }
}

const submitAlign = async () => {
  // 检查是否选择了文件（通过 raw 是否存在）
  if (!selectedFile1.value || !selectedFile2.value) {
    errorMessage.value = '请先选择两个文件';
    return
  }

  const formData = new FormData()
  formData.append('file1', selectedFile1.value)
  formData.append('file2', selectedFile2.value)
  formData.append('lang1', sourceLang.value)
  formData.append('lang2', targetLang.value)

  loading.value = true
  errorMessage.value = ''
  try {
    const res = await api.post('/align', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 300000 // 5分钟超时
    })
    result.value = res.data
    alignedPairs.value = res.data.aligned_pairs || []  //接收对齐结果
    ElMessage.success('对齐成功！')
  } catch (error) {
    console.error('对齐过程出错:', error)
    errorMessage.value = error.response?.data?.error || '对齐失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const downloadResult = async () => {
  try {
    window.open('/api/download-result')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败，请稍后重试')
  }
}
</script>

<style scoped>
.text-align {
  --primary: #a78bfa;
  --primary-light: #ddd6fe;
  --primary-dark: #7c3aed;
  --text: #1e293b;
  --bg: #fdf4ff;
  --card-bg: #ffffff;
  --border: #e2e8f0;
  --shadow: rgba(149, 157, 165, 0.2);
  max-width: 1100px;
  margin: 0 auto;
  padding: 24px;
}

.card {
  background: var(--card-bg);
  border-radius: 16px;
  box-shadow: 0 4px 20px var(--shadow);
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid var(--border);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 700;
  color: var(--primary-dark);
  margin-bottom: 12px;
}

.card-header.small {
  font-size: 16px;
}

.card-header .logo-img {
  width: 24px;
  height: 24px;
}

.sub-title {
  color: var(--text);
  font-weight: 400;
  font-size: 14px;
}

.lang-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 8px;
}

.select-area {
  border: 1px solid var(--border);
  background: var(--card-bg);
  border-radius: 12px;
  padding: 12px;
}

.select-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--primary-dark);
  font-weight: 600;
  margin-bottom: 10px;
}

.full-width :deep(.el-select) {
  width: 100%;
}
.full-width {
  width: 100%;
}

.upload-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 140px;
}

.upload-area {
  border: 2px dashed var(--primary);
  border-radius: 12px;
  padding: 18px;
  background-color: var(--primary-light);
  text-align: center;
}

.upload-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--primary-dark);
  font-weight: 600;
  margin-bottom: 12px;
}

.file-name {
  margin-top: 10px;
  font-size: 13px;
  color: #606266;
  max-width: 360px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.loading-indicator {
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.btn-group {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.btn-primary {
  background: var(--primary-dark);
}

.btn-primary:hover {
  background: var(--primary);
}

.mt-15 { margin-top: 15px; }

.result-section {
  margin-top: 8px;
  border-radius: 12px;
  overflow: hidden;
}

.result-box {
  border: 1px solid var(--border);
  background-color: var(--card-bg);
}

.result-toolbar {
  background-color: var(--primary-light);
  padding: 8px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--border);
}

.result-meta {
  padding: 12px 12px 0 12px;
}

.result-summary {
  margin-top: 8px;
  color: var(--text);
  font-size: 14px;
  padding: 0 2px;
}

@media (max-width: 1024px) {
  .text-align {
    padding: 16px;
  }
  .upload-grid {
    grid-template-columns: 1fr;
  }
  .lang-grid {
    grid-template-columns: 1fr;
  }
}
</style>

